package com.older.wptsb.service.impl;

import com.older.wptsb.config.AlertWebSocketHandler;
import com.older.wptsb.config.RabbitMQConfig;
import com.older.wptsb.domain.po.AlertLog;
import com.older.wptsb.mapper.AlertLogMapper;
import com.older.wptsb.mapper.CommunityElderMapper;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 预警消息接收器
 * 处理来自家庭端和社区端队列的预警消息，并通过WebSocket推送到前端
 */
@Service
public class AlertMessageReceiver {

    @Autowired
    private AlertLogMapper alertLogMapper;
    @Autowired
    private CommunityElderMapper communityElderMapper;

    /**
     * 处理家庭端预警消息
     * @param alertLog 预警日志
     */
    @RabbitListener(queues = RabbitMQConfig.ALERT_QUEUE_FAMILY)
    public void handleFamilyAlert(AlertLog alertLog) {
        System.out.println("收到家庭端预警消息: " + alertLog);

        // 构造推送消息
        Map<String, Object> message = new HashMap<>();
        message.put("type", "family_alert");
        message.put("data", alertLog);
        message.put("timestamp", System.currentTimeMillis());

        // 通过WebSocket向与该老人绑定的所有用户推送消息
        try {
            AlertWebSocketHandler.sendAlertToRelatedUsers(alertLog.getElderId(), message);
        } catch (IOException e) {
            System.err.println("推送家庭端预警消息失败: " + e.getMessage());
        }
    }

    /**
     * 处理社区端预警消息
     * @param alertLog 预警日志
     */
    @RabbitListener(queues = RabbitMQConfig.ALERT_QUEUE_COMMUNITY)
    public void handleCommunityAlert(AlertLog alertLog) {
        System.out.println("收到社区端预警消息: " + alertLog);

        // 保存预警日志到数据库
        alertLogMapper.insert(alertLog);

        // 构造推送消息
        Map<String, Object> message = new HashMap<>();
        message.put("type", "community_alert");
        message.put("data", alertLog);
        message.put("timestamp", System.currentTimeMillis());

        // 通过WebSocket推送到指定社区
        try {
            // 这里需要根据老人ID获取对应的社区ID
            String communityId = getCommunityIdByElderId(alertLog.getElderId());
            if (communityId != null) {
                AlertWebSocketHandler.sendAlertToCommunity(communityId, message);
            } else {
                // 如果无法获取社区ID，则广播给所有连接
                AlertWebSocketHandler.broadcastAlert(message);
            }
        } catch (IOException e) {
            System.err.println("推送社区端预警消息失败: " + e.getMessage());
        }
    }

    /**
     * 根据老人ID获取社区ID
     * 这里需要根据您的业务逻辑实现，例如查询数据库
     * @param elderId 老人ID
     * @return 社区ID
     */
    private String getCommunityIdByElderId(String elderId) {
        return communityElderMapper.selectCommunityIdByElderId(elderId); // 示例返回值
    }
}
